package com.gvtv.main;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.SchedulerException;

import com.gvtv.main.email.EmailThread;
import com.gvtv.main.quartz.QuartzService;
import com.gvtv.main.schedul.SchedulInfo;
import com.gvtv.main.util.AppTools;
import com.gvtv.main.util.PropertiesHelper;
import com.gvtv.main.xml.SchedulJobXmlParaser;

public class AnalysisMain {

private static final Logger logger = Logger.getLogger(AnalysisMain.class);
	
	private SchedulJobXmlParaser xmlParaser;
	private boolean isEmail = PropertiesHelper.getBoolean("mail.enable", false);
	public AnalysisMain(){
		xmlParaser = new SchedulJobXmlParaser();
	}
	
	public boolean checkXmlFile(File xmlFile){
		String fileName = xmlFile.getName();
		if(StringUtils.endsWithIgnoreCase(fileName, ".xml")){
			return true;
		}
		logger.warn(xmlFile.getAbsolutePath()+" is not a xml file, so ignore.");
		return false;
		
	}
	public List<File> getJobFiles(String[] args){
		File jobsFile = null;
		if(args!=null&&args.length>0){
			jobsFile = new File(args[0]);
			if(args.length>1){
				logger.warn("参数长度大于1,多余的参数无效.");
			}
		}else {
			jobsFile = new File(AppTools.getBaseDir()+"/jobs");
		}
		List<File> fileList = new ArrayList<File>();
		if(jobsFile.exists()){
			if(jobsFile.isDirectory()){
				File[] files = jobsFile.listFiles();
				for (File f : files) {
					if(checkXmlFile(f))
						fileList.add(f);
				}
			}else {
				if(checkXmlFile(jobsFile))
					fileList.add(jobsFile);
			}
		}else {
			logger.error(jobsFile.getAbsolutePath()+" 目录或文件不存在.");
		}
		return fileList;
	}
	private boolean checkScheduls(List<SchedulInfo> scheList){
		for (int i = 0; i < scheList.size(); i++) {
			for (int j = i+1; j < scheList.size(); j++) {
				if(scheList.get(i).getId().equals(scheList.get(j).getId())){
					return true;
				}
			}
		}
		return false;
	}

	public void run(String[] args) {
		xmlParaser.setFileList(this.getJobFiles(args));
		xmlParaser.paraser();
		List<SchedulInfo> scheList = xmlParaser.getSchedulList();
		if(scheList != null && scheList.size()>0){
			if(this.checkScheduls(scheList)){
				logger.error("调度id不唯一，请检查。。。" + scheList.toString());
				return ;
			}
			try {
				for (SchedulInfo schedulInfo : scheList) {
					QuartzService.getInstance().addSchedul(schedulInfo);
				}
				if(isEmail){
					EmailThread.getInstance().startup();
				}
				QuartzService.getInstance().start();
			} catch (SchedulerException e) {
				logger.error(e);
				QuartzService.getInstance().stop();
				if(isEmail){
					EmailThread.getInstance().stop();
				}
			}
		} else {
			logger.info("没有要调度的作业。");
		}
	}
	
	public static void main(String[] args) {
		AnalysisMain main = new AnalysisMain();
		main.run(args);
	}

}
